<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\CaptchaRequest;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class CaptchasController extends Controller {
    public function store(CaptchaRequest $request,CaptchaBuilder $captchaBuilder){
        $phone = $request->phone;
        $key = Str::random(15);
        $cacheKey = 'cc_'.$key;

        $captcha = $captchaBuilder->build();
        $expireAt = now()->addMinutes(2);
        $code = $captcha->getPhrase();

        Cache::put($cacheKey,compact('phone','code'),$expireAt);

        $result = [
            'captcha_key'=>$key,
            'expire_at'=>$expireAt->toDateTimeString(),
            'captcha_image_content'=>$captcha->inline()
        ];
        return response()->json($result)->setStatusCode(201);
    }

}
